import { Controller, Get, Param, Query, Req } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { RedisService } from 'src/redis/redis.service';
import { ChargeOrderRecord } from 'src/types';
import { errorReturn, successReturn } from 'src/utils';
import { ChargeOrderService } from './charge-order.service';

@Controller('chargeOrder')
export class ChargeOrderController {
    private chargingOrderKey = '';
    constructor(
        private chargeOrderService:ChargeOrderService,
        private configService:ConfigService,
        private redis:RedisService,
    ) {
        this.chargingOrderKey = this.configService.get('redisKey.charge.chargingOrder')
    }

    @Get('page')
    async page(@Query() query:Pagination, @Req() { userId }) {
        let rows = await this.chargeOrderService.page(query, userId)
        return successReturn(rows)
    }

    async singleCharging(orderId:number, userId:number) {
        let order = await this.chargeOrderService.order(orderId, ['userId', 'orderId', 'orderNo', 'createTime', 'status', 'deviceId', 'portNo', 'chargeAmount', 'strategyType'])
        if(order.status != 1 || order.userId != userId) return null
        const realTimeInfo:any = await this.chargeOrderService.realTimeInfo(orderId)
        if(realTimeInfo) {
            order.realTimeInfo = realTimeInfo.lastData
        }

        return order
    }



    @Get('charging')
    async charging(@Query('orderId') orderId:number, @Req() {userId}) {
        if(orderId) { //单个充电中
            return successReturn(await this.singleCharging(orderId, userId))
        }else { //全部充电中
            const key = this.chargingOrderKey + userId
            let orderIds = await this.redis.store.lRange(key, 0, -1)
            const len = orderIds.length
            if(len == 0) return errorReturn()
            if(len == 1) {
                return successReturn([await this.singleCharging(Number(orderIds[0]), userId)])
            }

            const orders:ChargeOrderRecord[] = []
            const orderList = await this.chargeOrderService.chargingOrder(orderIds.map(orderId => Number(orderId)))
            
            if(orderList.length > 0) {
                orderList.forEach(order => {
                    if(order.status != 1) {
                        this.redis.store.lRem(key, 0, String(order.orderId))
                    }else {
                        orders.push(order)
                    }
                })

                if(orders.length > 0) {
                    const realTimeInfos:any = await this.chargeOrderService.realTimeInfo(orders.map(order => order.orderId))
                    if(realTimeInfos) {
                        orders.forEach(order => {
                            for(let i = 0; i < realTimeInfos.length; i ++) {
                                if(order.orderId == realTimeInfos[i]._id) {
                                    order.realTimeInfo = realTimeInfos[i].lastData
                                    realTimeInfos.splice(i, 0)
                                    break
                                }
                            }
                        })
                    }
                }

            }

            return successReturn(orders)
        }
        
    }

    @Get('order/:orderId')
    async order(@Param('orderId') orderId:number, @Req() { userId }) {
        const order = await this.chargeOrderService.order(orderId, userId)
        return successReturn(order)
    }

    @Get('power/:orderId')
    async power(@Param('orderId') orderId:number) {
        const data = await this.chargeOrderService.power(orderId)
        return successReturn(data)
    }
}
